package com.fingard.dsp.bank.directbank.alipay01;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.fingard.dsp.bank.directConfig.ActSetItem;
import com.fingard.dsp.bank.directbank.bankInterface.IGateway;
import com.fingard.dsp.bank.reqrespobj.gateway.ReqGateway;
import com.fingard.dsp.bank.reqrespobj.unifiedorder.ReqQueryOrder;
import com.fingard.dsp.bank.reqrespobj.unifiedorder.RetAtsQueryOrder;
import com.fingard.text.StringHelper;
import net.sf.json.JSONObject;

import java.util.HashMap;

public class ALIPAY01Gateway extends ALIPAY01Base implements IGateway {
	@Override
	public HashMap<String, String> GenGwMap(ReqGateway p_reqGateway) throws Exception {
		HashMap<String, String> retMap = new HashMap<String, String>();
		
		try {
			logIsExist();

			String ownAct = p_reqGateway.reqHashMap.get("OurBankAccount");
			ActSetItem actItem = this.getBankConfig().getActSetItem(ownAct, "unifiedorder");
			if (actItem != null) {
				String signType = "RSA";
            	boolean useSignType = getBankConfig().getValueAsBool("useSignType");
            	if (useSignType) {
            		signType = actItem.signType;
            	}
            	
				AlipayClient alipayClient = new DefaultAlipayClient(bankFront.serverURL, actItem.appId, 
						actItem.ownKeyStorePath, "json", getCharset(), actItem.oppCertFilePath, signType);
				
				JSONObject alipayJsonRequest = new JSONObject();
				alipayJsonRequest.put("out_trade_no", p_reqGateway.reqHashMap.get("RdSeq"));
				alipayJsonRequest.put("product_code", "FAST_INSTANT_TRADE_PAY");
				alipayJsonRequest.put("total_amount", p_reqGateway.reqHashMap.get("Amount"));
				alipayJsonRequest.put("subject", p_reqGateway.reqHashMap.get("Description"));
				alipayJsonRequest.put("body", p_reqGateway.reqHashMap.get("Attach"));
				String enable_pay_channels = getBankConfig().getValueAsString("enablePayChannels");
				if(!StringHelper.isNullOrEmpty(enable_pay_channels)){
					alipayJsonRequest.put("enable_pay_channels", enable_pay_channels);
				}
				alipayJsonRequest.put("timeout_express", getValidTime(p_reqGateway.getValidTime()));
				
				if(StringHelper.hasAnyChar(p_reqGateway.reqHashMap.get("InsureAreaCode")) || StringHelper.hasAnyChar(p_reqGateway.reqHashMap.get("SHTradeNo"))) {
					StringBuilder insuranceMsg = new StringBuilder();
					insuranceMsg.append("\"{\\\"insuranceFlag\":\"T\"," +
							"\"insureAreaCode\":\""+p_reqGateway.reqHashMap.get("InsureAreaCode")+"\"," +
							"\"insuranceType\":\"alipay_auto_ins\",\"shTradeNo\":\""+p_reqGateway.reqHashMap.get("SHTradeNo")+"\"}\"");
					JSONObject insuranceInfo = new JSONObject();
					insuranceInfo.put("insurance_info", insuranceMsg.toString());
					alipayJsonRequest.put("extend_params", insuranceInfo);
				}
				
				WriteBankLogStep2(JSON.toJSONString(alipayJsonRequest));
				
				AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
				alipayRequest.setReturnUrl(actItem.returnURL);
				alipayRequest.setNotifyUrl(actItem.notifyURL);
				
				String bizContent = JSON.toJSONString(alipayJsonRequest);
				bizContent = bizContent.replaceAll("\\\\\\\\", "");
				
				alipayRequest.setBizContent(bizContent);
				WriteBankUrlLogLn(bankFront.serverURL);
				WriteBankLogStep2(alipayRequest.getBizContent());
				
				String result = alipayClient.pageExecute(alipayRequest).getBody();
				WriteBankLogStep3(result);
				
				if (result.length() > 0) {
					retMap.put("RespCode", "0");
					retMap.put("RespInfo", "签名成功");
					retMap.put("Result", result);
				} else {
					retMap.put("RespCode", "-1");
					retMap.put("RespInfo", "签名失败");
				}
			} else {
				retMap.put("RespCode", "0");
				retMap.put("RespInfo", "未找到账号[" + ownAct + "]商户配置信息");
				retMap.put("Result", "");
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			retMap.put("RespCode", "-1");
			retMap.put("RespInfo", ex.getMessage());
			WriteBankLogLn(ex);
		}
		
		return retMap;
	}

	@Override
	public RetAtsQueryOrder queryGWPay(ReqQueryOrder p_reqGateway) throws Exception {
		RetAtsQueryOrder retAts = new RetAtsQueryOrder();
		retAts.rdSeq = p_reqGateway.rdSeq;

		try {
			logIsExist();

			ActSetItem actItem = getBankConfig().getActSetItem(p_reqGateway.ownAct, "unifiedorder");
			if (actItem != null) {
				String signType = "RSA";
            	boolean useSignType = getBankConfig().getValueAsBool("useSignType");
            	if (useSignType) {
            		signType = actItem.signType;
            	}
            	
				AlipayClient alipayClient = new DefaultAlipayClient(bankFront.serverURL, actItem.appId, 
						actItem.ownKeyStorePath, "json", getCharset(), actItem.oppCertFilePath, signType);
				
				AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
				request.setBizContent("{\"out_trade_no\":\"" + p_reqGateway.rdSeq + "\"}");

				WriteBankUrlLogLn(bankFront.serverURL);
				WriteBankLogStep2(request.getBizContent());

				AlipayTradeQueryResponse response = alipayClient.execute(request);
				WriteBankLogStep3(response.getBody());

				retAts.respCode = "0";
				retAts.respInfo = response.getMsg();
				if ("10000".equals(response.getCode())) {
					retAts.transState = StringHelper.joinNotEmpty("+", response.getCode(), response.getTradeStatus());
					retAts.payInfoCode = response.getTradeStatus();
					retAts.outTransID = response.getTradeNo();
				} else {
					retAts.transState = StringHelper.joinNotEmpty("+", response.getCode(), response.getSubCode());
					retAts.payInfoCode = response.getSubCode();
				}
			} else {
				retAts.respCode = "-1";
				retAts.respInfo = "未找到账号[" + p_reqGateway.ownAct + "]商户配置信息";
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			retAts.respCode = "-1";
			retAts.respInfo = ex.getMessage();
			WriteBankLogLn(ex);
		}

		return retAts;
	}
}
